import 'package:flutter/material.dart';

class AnimatedModelBarrierDemo extends StatefulWidget {
  AnimatedModelBarrierDemo({Key? key}) : super(key: key);

  @override
  _AnimatedModelBarrierDemoState createState() =>
      _AnimatedModelBarrierDemoState();
}

class _AnimatedModelBarrierDemoState extends State<AnimatedModelBarrierDemo>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller =
      AnimationController(duration: const Duration(seconds: 1), vsync: this);

  //使用自定义曲线动画过渡效果
  late Animation<Color?> _colorAnimation;
  bool _isLoading = false;
  late Widget _animatedModalBarrier;

  @override
  void initState() {
    _colorAnimation = ColorTween(
      begin: Colors.black.withAlpha(50),
      end: Colors.black.withAlpha(80),
    ).animate(_controller);

    _animatedModalBarrier = AnimatedModalBarrier(
      color: _colorAnimation,
      dismissible: true,
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('SizeTransition'),
        brightness: Brightness.dark,
        backgroundColor: Colors.blue,
      ),
      body: Center(
        child: Container(
          height: 100.0,
          width: 250.0,
          child: Stack(
            alignment: Alignment.center,
            children: _buildStackChildren(),
          ),
        ),
      ),
    );
  }

  List<Widget> _buildStackChildren() {
    List<Widget> widgets = <Widget>[
      TextButton(
        style: ButtonStyle(
          backgroundColor: MaterialStateColor.resolveWith((states) {
            if (states.contains(MaterialState.pressed)) {
              return Colors.blue[600]!;
            }
            return Colors.blue;
          }),
          foregroundColor: MaterialStateColor.resolveWith((states) {
            return Colors.white;
          }),
        ),
        child: Text('Press'),
        onPressed: () {
          setState(() {
            _isLoading = true;
          });

          _controller.reset();
          _controller.forward();

          ScaffoldMessenger.of(context).showSnackBar(SnackBar(
            content: Text('点击按钮!'),
          ));

          Future.delayed(const Duration(seconds: 3), () {
            if (mounted) {
              setState(() {
                _isLoading = false;
              });
            }
          });
        },
      ),
    ];

    if (_isLoading) {
      widgets.add(_animatedModalBarrier);
      widgets.add(Container(
        alignment: Alignment.center,
        color: Colors.white,
        child: Text('这是遮罩之上的组件'),
        width: 200,
        height: 80,
      ));
    }

    return widgets;
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}
